/**
 * author:Administrator
 * date:2016/3/29
 * desc:TODO
 */
'use strict';

let service = {};
module.exports = service;

let query = require('../infrastructure/query');
let categoryRepo = require('../domain/model_cmd/category/categoryRepo.js');
let locationRepo = require('../../ddd/domain/model_cmd/location/locationRepo.js');
let customerRepo = require('../domain/model_cmd/customer/customerRepo.js');
let managerRepo = require('../domain/model_cmd/manager/managerRepo.js');
let vendorRepo = require('../domain/model_cmd/vendor/vendorRepo.js');
let shopkeeperRepo = require('../domain/model_cmd/shopkeeper/shopkeeperRepo.js');


/**
 * 查询所有category
 * @returns {Array}
 */
service.allCategory = function*() {
  return yield query.category.findAll();
};

/**
 * 查询顶级category
 * @returns {Array}
 */
service.topCategory = function*() {
  return yield query.category.findRoot();
};

/**
 * 查询某个category所有 直接、简介 child
 * @param {Number} pid
 * @returns {Array}
 */
service.childCategory = function*(pid) {
  return yield query.category.findChild(pid);
};

/**
 * 查询一个category
 * @param {Number} id
 * @returns {Object}
 */
service.oneCategory = function*(id) {
  return yield categoryRepo.find(id);
};

/**
 * 查询所有 location
 * @returns {Array}
 */
service.allLocation = function*() {
  return yield query.location.findAll();
};

/**
 * 查询顶级 location
 * @returns {Array}
 */
service.topLocation = function*() {
  return yield query.location.findRoot();
};

/**
 * 查询某个 location 所有 直接、简介 child
 * @param {Number} pid
 * @returns {Array}
 */
service.childLocation = function*(pid) {
  return yield query.location.findChild(pid);
};

/**
 * 查询一个 location
 * @param {Number} id
 * @returns {Object}
 */
service.oneLocation = function*(id) {
  return yield locationRepo.find(id);
};

/**
 * 获取某个 user的所有 role
 * @param {Number} uId
 * @return {Object}
 */
service.allUserRole = function *(uId) {
  let result = {};
  result.customer = yield customerRepo.findByUid(uId);
  result.manager = yield managerRepo.findByUid(uId);
  result.vendor = yield vendorRepo.findByUid(uId);
  result.shopkeeper = yield shopkeeperRepo.findByUid(uId);
  return result;
};

/**
 * 根据参数获取role
 * @param {String}  type  customer/vendor/manager/shopkeeper
 * @param {Number}  uId
 * @param {Number}  id
 * @return {Object}
 */
service.getRole = function*(type, uId, id) {
  type = type.toLowerCase();
  let role;
  switch (type) {
    case 'customer':
      role = yield customerRepo.find(id);
      break;
    case 'manager':
      role = yield managerRepo.find(id);
      break;
    case 'vendor':
      role = yield vendorRepo.find(id);
      break;
    case 'shopkeeper':
      role = yield shopkeeperRepo.find(id);
      break;
  }
  if (role.uId == uId) {
    return role;
  }
  return null;
};